package com.osi.project.redis.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.osi.project.common.business.RedisClient;
import com.osi.project.redis.generate.pojo.RedisSlowLogDO;
import com.osi.start.common.util.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.osi.start.framework.business.service.BaseServiceImpl;
import com.osi.project.redis.manager.RedisSlowLogManager;
import com.osi.project.redis.service.RedisService;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.util.Slowlog;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @Desc：大部分的核心业务逻辑处理，对多个biz组成处理，可为inner/api/admin层提供核心服务接口
 * @author pwh
 * @date 2018年01月01日 09:09:09
 * @Copyright (c) onestop
 */
@Slf4j
@Service
public class RedisServiceImpl extends BaseServiceImpl implements RedisService {

    @Autowired
    private RedisSlowLogManager redisSlowLogManager;
    @Autowired
    private RedisClient redisClient;

    @Override
    public List<RedisSlowLogDO> queryAndSaveAllSlowSql() {
        List<RedisSlowLogDO> redisSlowLogDOList = new ArrayList<>();

        Set<String> paramsMd5 = new HashSet<>();

        List<Jedis> jedisList = redisClient.getJedis();
        for (Jedis jedis : jedisList) {
            List<Slowlog> slowlogList = jedis.slowlogGet(10);
            for (Slowlog slowlog : slowlogList) {
                RedisSlowLogDO redisSlowLogDO = new RedisSlowLogDO();
                redisSlowLogDO.setId(generateId());
                redisSlowLogDO.setStartTime(new Date(slowlog.getTimeStamp() * 1000));
                redisSlowLogDO.setLogId(slowlog.getId());
                redisSlowLogDO.setDuration(slowlog.getExecutionTime());  //微秒
                redisSlowLogDO.setParams(JSONObject.toJSONString(slowlog.getArgs()));
                redisSlowLogDO.setParamsMd5(MD5.md5(redisSlowLogDO.getParams()));
                redisSlowLogDO.initCreateEntitySysData();

                boolean exist = paramsMd5.add(redisSlowLogDO.getParamsMd5());
                if (!exist) {
                    continue;
                }
                redisSlowLogDOList.add(redisSlowLogDO);
            }
        }
        redisSlowLogManager.getCommonDao().addBatchIgnorePrimaryKey(redisSlowLogDOList);
        return redisSlowLogDOList;
    }

    @PostConstruct
    public void startWork() {
        new Thread(() -> {
            try {
                //2分钟处理一次
                Thread.sleep(120000);
            } catch (InterruptedException e) {
                System.out.printf(e.getMessage());
            }

            log.info("------->startWork");
            queryAndSaveAllSlowSql();
        }).start();
    }

}
